package communi;

/**
 * @author Mark
 * @version 1.0
 * @date 2020/5/24 12:08
 * @description 线程通信(生产者消费者模式)
 */
public class ThreadCom {

    public static void main(String[] args) {
        SyncContainer syncCon = new SyncContainer();
        new Product(syncCon).start();
        new Consumer(syncCon).start();

    }
}

class Product extends Thread {

    private SyncContainer syncCon;

    Product(SyncContainer syncCon) {
        this.syncCon = syncCon;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            syncCon.push(new Chicken(i));
            System.out.println("生产了" + i + "只鸡");
        }
    }
}

class Consumer extends Thread {

    private SyncContainer syncCon;

    Consumer(SyncContainer syncCon) {
        this.syncCon = syncCon;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("消费了" + syncCon.pop().num + "只鸡");
        }
    }

}

class Chicken {

    int num;

    Chicken(int num) {
        this.num = num;
    }
}

class SyncContainer {

    private int count = 0;

    private Chicken[] chickens = new Chicken[10];

    synchronized void push(Chicken chicken) {
        // 容器慢需要等待
        if (count == chickens.length) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        chickens[count] = chicken;
        count++;
        this.notifyAll();
    }

    synchronized Chicken pop() {
        // 容器慢需要等待
        if (count == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        count--;
        this.notifyAll();
        return chickens[count];
    }

}

